package while_lang.ast;

import java.util.Map;
import java.util.Random;

/** Nodo del AST de While que representa una sentencia condicional.
 *  @author Leonardo Val
 */
public class IfThenElse extends Stmt {	
	public final Exp condition;
	public final Stmt thenBody, elseBody;
	
	public IfThenElse(Exp condition, Stmt thenBody, Stmt elseBody) {
		this.condition = condition;
		this.thenBody = thenBody;
		this.elseBody = elseBody;
	}
	
	@Override public String unparse() {
		return "if "+ condition.unparse() +" then "+ thenBody.unparse() +" else "+ elseBody.unparse();
	}

	@Override public void halteadNumbers(Map<String, Integer> operands, Map<String, Integer> operators) {
		condition.halteadNumbers(operands, operators);
		thenBody.halteadNumbers(operands, operators);
		elseBody.halteadNumbers(operands, operators);
		String key = "IfThenElse";
		Stmt.incrementarDiccionario(key, operators);
	}
	
	public static IfThenElse generate(Random random, int min, int max) {
		return new IfThenElse(
			Exp.generate(random, min-1, max-1),
			Stmt.generate(random, min-1, max-1),
			Stmt.generate(random, min-1, max-1)
		);
	}
	
	@Override public String toString() {
		return "IfThenElse("+ condition +", "+ thenBody +", "+ elseBody +")";
	}

	@Override public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((condition == null) ? 0 : condition.hashCode());
		result = prime * result
				+ ((elseBody == null) ? 0 : elseBody.hashCode());
		result = prime * result
				+ ((thenBody == null) ? 0 : thenBody.hashCode());
		return result;
	}

	@Override public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		IfThenElse other = (IfThenElse) obj;
		if (condition == null) {
			if (other.condition != null)
				return false;
		} else if (!condition.equals(other.condition))
			return false;
		if (elseBody == null) {
			if (other.elseBody != null)
				return false;
		} else if (!elseBody.equals(other.elseBody))
			return false;
		if (thenBody == null) {
			if (other.thenBody != null)
				return false;
		} else if (!thenBody.equals(other.thenBody))
			return false;
		return true;
	}
	
}
